package org.dragonnova.lamp;

import android.os.Handler;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * Created by hucn on 2016/10/25.
 * Description:
 */
public class defaultDelivery implements MessageDelivery {

    private Executor executor;
    private LampListener listener;

    public defaultDelivery(Executor executor) {
        this.executor = executor;
    }

    public void setLampListener(LampListener listener) {
        this.listener = listener;
    }

    public defaultDelivery(final Handler handler) {
        // Make an Executor that just wraps the handler.
        executor = new Executor() {
            @Override
            public void execute(Runnable command) {
                handler.post(command);
            }
        };
    }

    @Override
    public void postResponse(List<Lamp> lamps) {
        executor.execute(new DeliveryRunnable(lamps, null));
    }

    @Override
    public void postError(ErrorCode error) {
        executor.execute(new DeliveryRunnable(null, error));
    }


    private class DeliveryRunnable implements Runnable {
        private List<Lamp> lamps;
        private Lamp lamp;
        private ErrorCode error;

        public DeliveryRunnable(List<Lamp> lamps, ErrorCode error) {
            this.lamps = lamps;
            this.error = error;
        }

        @Override
        public void run() {
            if (error == null) {
                listener.onRefresh(lamps);
            } else {
                listener.onError(error);
            }
        }
    }
}
